const app = getApp()
import { getAddres, getStsInformation, supplierCheckIsExist } from '../../api/index.js'
import { filterMobile, filterEmail, specialPlane, filterMobileOrEmail } from '../../utils/util'
Page({
  data: {
    form: {
      companyName: '',
      province: '',
      city: '',
      area: '',
      detailAddress: '',
      mobile: '',
      companyMail: '',
      companyUrl: '',
      personsInChargeOfCompany: '',
      personsInChargeOfCompanyPhoneAndMail: '',
      saleInChargeOfCompany: '',
      saleInChargeOfCompanyPhoneAndMail: '',
      qualityInChargeOfCompany: '',
      qualityInChargeOfCompanyPhoneAndMail: '',
      headOfSales: '',
      headOfSalesPhoneAndMail: '',
      registeredFund: '',
      companyCreateDate: '',
      companyType: '',
      generalTaxpayer: '',
    },
    qualityIndex: '',
    region: [],
    multiIndex: [],
    multiArray: [[], [], []],
    qualitys: [],
    province: '',
    city: '',
    area: '',
    isCompany: false
  },
  async save() {},
	async getSelectList() {
    try {
      const { ResultSet } = await getStsInformation()
      this.setData({
        selects: ResultSet.userData
      })
    } catch (err) {
      console.log(err)
    }
  },
  bindRegionChange ({ detail: { value } }) {
    let province = ''
    let provinceId = ''
    let city = ''
    let cityId = ''
    let area = ''
    let areaId = ''
    value.forEach((item, index) => {
      if (index === 0) {
        province = this.data.multiArray[index][item].name
        provinceId = this.data.multiArray[index][item].id
      }
      if (index === 1) {
        city = this.data.multiArray[index][item].name
        cityId = this.data.multiArray[index][item].id
      }
      if (index === 2) {
        area = this.data.multiArray[index][item].name
        areaId = this.data.multiArray[index][item].id
      }
    })
    this.setData({
      multiIndex: value,
      province: province,
      city: city,
      area: area,
      'form.province': provinceId,
      'form.city': cityId,
      'form.area': areaId
    })
  },
  async changeColumn ({ detail: { column, value } }) {
    if (column + 1 === 1) {
      await this.getCity(column + 1, this.data.multiArray[column][value].id)
      this.getArea(column + 2, this.data.multiArray[column + 1][0].id)
    }
    if (column + 1 === 2) this.getArea(column + 1, this.data.multiArray[column][value].id)
  },
  changeInput ({ detail: { value }, target: { dataset: { key } } }) {
    if (key === 'companyName') {
      this.postSupplierCheckIsExist(value, key)
    } else {
      this.setData({
        ['form.' + key]: value
      })
    }
  },
  async postSupplierCheckIsExist (value, key) {
    try {
      await supplierCheckIsExist({ companyName: value })
      this.setData({
        ['form.' + key]: value,
        isCompany: true
      })
    } catch (err) {
      this.setData({
        isCompany: false
      })
      wx.showToast({ title: err.messages || err.ResultSet.errors, icon: 'none' })
    }
  },
  bindDateChange ({ detail: { value } }) {
    this.setData({
      'form.companyCreateDate': value
    })
  },
  changeCompanyType ({ detail: { value } }) {
    this.setData({
      qualityIndex: value,
      'form.companyType': this.data.qualitys[value].dictionaryId
    })
  },
  changeRadio ({ detail: { value } }) {
    this.setData({
      'form.generalTaxpayer': JSON.parse(value)
    })
  },
  nextStep () {
    let mobileValid = filterMobile(this.data.form.mobile) || specialPlane(this.data.form.mobile)
    let emailValid = filterEmail(this.data.form.companyMail)
    let filters = ['companyName', 'province', 'city', 'area', 'detailAddress', 'companyUrl', 'personsInChargeOfCompany', 'saleInChargeOfCompany', 'headOfSales', 'registeredFund', 'companyCreateDate', 'companyType']
    let valid = filters.every(key => this.data.form[key])
    let mobileFilters = ['personsInChargeOfCompanyPhone', 'saleInChargeOfCompanyPhone', 'headOfSalesPhone']
    let emailFilters = ['personsInChargeOfCompanyMail', 'saleInChargeOfCompanyMail', 'headOfSalesMail']
    let hybridMobileValid = mobileFilters.every(key => filterMobile(this.data.form[key]))
    let hybridEmailValid = emailFilters.every(key => filterEmail(this.data.form[key]))
    console.log(hybridMobileValid)
    let saleValid = true
    if (this.data.form.qualityInChargeOfCompanyPhone) {
      saleValid = filterMobile(this.data.form.qualityInChargeOfCompanyPhone) && filterEmail(this.data.form.qualityInChargeOfCompanyMail)
    } else {
      saleValid = true
    }
    if (!this.data.isCompany) {
      wx.showToast({ title: '请勿重复填写，公司已存在', icon: 'none' })
      return
    }
    if (!mobileValid || !hybridMobileValid) {
      wx.showToast({ title: '请仔细检查是否有电话号码错误！', icon: 'none' })
      return
    }
    if (!emailValid || !hybridEmailValid) {
      wx.showToast({ title: '请仔细检查是否有邮箱错误！', icon: 'none' })
      return
    }
    if (!saleValid) {
      wx.showToast({ title: '请仔细检查是否有电话号码或者邮箱错误！', icon: 'none' })
      return
    }
    if (this.data.form.generalTaxpayer === '' || !valid ) {
      wx.showToast({ title: '请仔细检查是否有未填写的数据！', icon: 'none' })
      return
    }
    app.globalData.form = { ...app.globalData.form, ...this.data.form }
    wx.$nav.navigateTo('/pages/sales/index')
  },
  async getAddres () {
    try {
      const { ResultSet } = await getAddres()
      this.setData({
        'multiArray[0]': ResultSet.userData.getAddreList
      })
      let id = ''
      if (this.data.form.province) {
        let item = ResultSet.userData.getAddreList.find(item => item.id === this.data.form.province)
        this.setData({
          province: item.name
        })
        id = this.data.form.province
      } else {
        id = ResultSet.userData.getAddreList[0].id
      }
      await this.getCity(1, id)
      // await this.getChildAddress(2, id)
    } catch (err) {
      console.log(err)
    }
  },
  async getCity (index, id) {
    try {
      const { ResultSet } = await getAddres({ content: { id } })
      const temp = `multiArray[${index}]`
      this.setData({
        [temp]: ResultSet.userData.getAddreList
      })
      let paramsId = ''
      if (this.data.form.city) {
        paramsId = this.data.form.city
        let item = ResultSet.userData.getAddreList.find(item => item.id === this.data.form.city)
        this.setData({
          city: item.name
        })
      } else {
        paramsId = ResultSet.userData.getAddreList[0].id
      }
      await this.getArea(2, paramsId)
    } catch (err) {
      console.log(err)
    }
  },
  async getArea (index, id) {
    try {
      const { ResultSet } = await getAddres({ content: { id } })
      const temp = `multiArray[${index}]`
      this.setData({
        [temp]: ResultSet.userData.getAddreList
      })
      if (this.data.form.area) {
        let item = ResultSet.userData.getAddreList.find(item => item.id === this.data.form.area)
        this.setData({
          area: item.name
        })
      }
    } catch (err) {
      console.log(err)
    }
  },
  onShow() {
    const { form, dropDown } = app.globalData
    if (dropDown.companyTypeList.length) {
      if (form.companyType) {
        this.setData({
          qualityIndex: dropDown.companyTypeList.findIndex(item => item.dictionaryId === form.companyType) > -1 ? dropDown.companyTypeList.findIndex(item => item.dictionaryId === form.companyType) : ''
        })
      }
      this.setData({
        qualitys: dropDown.companyTypeList
      })
    } else {
      app.globalData.getDropDownCallback = res => {
        this.setData({
          qualitys: app.globalData.dropDown.companyTypeList,
          qualityIndex: dropDown.companyTypeList.findIndex(item => item.dictionaryId === form.companyType) > -1 ? dropDown.companyTypeList.findIndex(item => item.dictionaryId === form.companyType) : ''
        })
      }
    }
    this.setData({
      form: form,
    })
    if (form.province) {
      this.setData({
        multiIndex: [form.province, form.city, form.area]
      })
    }
    this.getSelectList()
    this.getAddres()
  },
})
